-module(errlogs).
-export([start_errlog/1, start_errlog/2, end_errlog/0, errlog/1, errlog/2]).

start_errlog(Name) ->
	FPid = self(),
	Pid = spawn(fun() -> errlog_loop(Name, FPid, false) end),
	register(errlog, Pid),
	receive
		errlog_ok ->
			Pid;
		{errlog_error, Reason} ->
			{errlog_error, Reason}
	end.
start_errlog(Name, IsDebug) ->
	FPid = self(),
	Pid = spawn(fun() -> errlog_loop(Name, FPid, IsDebug) end),
	register(errlog, Pid),
	receive
		errlog_ok ->
			Pid;
		{errlog_error, Reason} ->
			{errlog_error, Reason}
	end.

end_errlog() ->
	errlog ! errlog_end.

print_datetime() ->
	{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:local_time(),
	io:format("~p/~p/~p ~p:~p:~p ", [Year, Month, Day, Hour, Minute, Second]).
print_datetime(IoDevice) ->
	{{Year, Month, Day}, {Hour, Minute, Second}} = calendar:local_time(),
	io:format(IoDevice, "~p/~p/~p ~p:~p:~p ", [Year, Month, Day, Hour, Minute, Second]).

errlog_loop() ->
	receive
		{errlog_msg, Format, ColMsg} ->
			print_datetime(),
			io:format(Format, ColMsg),
			errlog_loop();
		{errlog_msg, Message} ->
			print_datetime(),
			io:format(Message, []),
			errlog_loop();
		errlog_end ->
			ok;
		Other ->
			print_datetime(),
			io:format("unknown error_log command(~p).~n", [Other]),
			errlog_loop()
	end.
errlog_loop(IoDevice) ->
	receive
		{errlog_msg, Format, ColMsg} ->
			print_datetime(IoDevice),
			io:format(IoDevice, Format, ColMsg),
			errlog_loop(IoDevice);
		{errlog_msg, Message} ->
			print_datetime(IoDevice),
			io:format(IoDevice, Message, []),
			errlog_loop(IoDevice);
		errlog_end ->
			file:close(IoDevice);
		Other ->
			print_datetime(IoDevice),
			io:format(IoDevice, "unknown error_log command(~p).~n", [Other]),
			errlog_loop(IoDevice)
	end.
errlog_loop(_, FPid, true) ->
	FPid ! errlog_ok,
	errlog_loop();
errlog_loop(Name, FPid, false) ->
	case file:open(Name, [write, append, binary]) of
		{ok, IoDevice} ->
			FPid ! errlog_ok,
			errlog_loop(IoDevice);
		{error, Reason} ->
			FPid ! {errlog_error, Reason}
	end.

errlog(Format, ColMsg) ->
	errlog ! {errlog_msg, Format, ColMsg}.

errlog(Message) ->
	errlog ! {errlog_msg, Message}.

